package main

import (
	"fmt"
	"github.com/hajimehoshi/oto"
	"github.com/tosone/minimp3"
	"image/color"
	"io/ioutil"
	"log"
	"time"

	"gocv.io/x/gocv"
)

func main() {
	// set to use a video capture device 0
	deviceID := 0

	// open webcam
	webcam, err := gocv.OpenVideoCapture(deviceID)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer webcam.Close()

	// 新建一个摄像头窗口
	//window := gocv.NewWindow("Face Detect")
	//defer window.Close()

	// prepare image matrix
	img := gocv.NewMat()
	defer img.Close()

	// color for the rect when faces detected
	blue := color.RGBA{0, 0, 255, 0}

	// load classifier to recognize faces
	classifier := gocv.NewCascadeClassifier()
	defer classifier.Close()
	//haarcascade_frontalface_default.xml
	if !classifier.Load("data/haarcascade_frontalface_alt2.xml") {
		fmt.Println("没找到配置文件: data/haarcascade_frontalface_default.xml")
		return
	}

	fmt.Printf("开始读取摄像头数据: %v\n", deviceID)
	for {
		if ok := webcam.Read(&img); !ok {
			fmt.Printf("找不到摄像头 %v\n", deviceID)
			return
		}
		if img.Empty() {
			continue
		}

		// 检测人脸
		rects := classifier.DetectMultiScale(img)
		//fmt.Printf("当前人脸数 %d \n", len(rects))
		if len(rects) > 2 {
			fmt.Println("指点江山激扬文字，你背后有人。。。。。。。。。。。。。", time.Now())
			PlayMp3()
		}
		// 脸上画个蓝色的方框
		for _, r := range rects {
			gocv.Rectangle(&img, r, blue, 3)
		}

		// 显示图片
		//window.IMShow(img)
		//window.WaitKey(1)
	}

}
func PlayMp3() {
	var err error

	var dec *minimp3.Decoder
	var data, file []byte
	var player *oto.Player

	if file, err = ioutil.ReadFile("data/aigei.mp3"); err != nil {
		log.Fatal(err)
	}

	if dec, data, err = minimp3.DecodeFull(file); err != nil {
		log.Fatal(err)
	}

	if player, err = oto.NewPlayer(dec.SampleRate, dec.Channels, 2, 1024); err != nil {
		log.Fatal(err)
	}
	player.Write(data)

	<-time.After(time.Second)
	dec.Close()
	player.Close()
}
func PlayMp32(){
	var file, _ = ioutil.ReadFile("data/aigei.mp3.mp3")
	dec, data, _ := minimp3.DecodeFull(file)

	player, _ := oto.NewPlayer(dec.SampleRate, dec.Channels, 2, 1024)
	player.Write(data)
	<-time.After(time.Second)
	dec.Close()
	player.Close()
}
